package com.ex.managersystem1024.common;

import cn.hutool.crypto.SecureUtil;
import com.ex.managersystem1024.entity.User;
import com.ex.managersystem1024.mapper.UserMapper;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.ObjectWriter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Component;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.URISyntaxException;
import java.util.Date;

@Component
public class DefaultUserInitializer implements ApplicationRunner {

    @Autowired
    private UserMapper userMapper;

    @Override
    public void run(ApplicationArguments args) throws Exception {
        try {
            // 获取配置文件的输入流
            InputStream inputStream = getClass().getResourceAsStream("/config.json");

            ObjectMapper objectMapper = new ObjectMapper();
            Config config = objectMapper.readValue(inputStream, Config.class);

            if (config.isCreateDefaultUser()) {
                User user = User.builder()
                        .username("admin")
                        .password(SecureUtil.md5("123456"))
                        .phone("1234567890")
                        .email("admin@example.com")
                        .avatar("default_avatar.jpg")
                        .createdAt(new Date())
                        .build();

                userMapper.insert(user);
                config.setCreateDefaultUser(false);
                ObjectWriter objectWriter = objectMapper.writerWithDefaultPrettyPrinter();
                objectWriter.writeValue(new File(getClass().getResource("/config.json").toURI()), config);
                System.out.println("配置文件已更新！");
            }
        } catch (IOException | URISyntaxException e) {
            e.printStackTrace();
        }
    }

    public static class Config {
        private boolean createDefaultUser;

        public boolean isCreateDefaultUser() {
            return createDefaultUser;
        }

        public void setCreateDefaultUser(boolean createDefaultUser) {
            this.createDefaultUser = createDefaultUser;
        }
    }
}
